package com.gene.tlonpo.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;

import com.gene.tlonpo.config.LonpoStaticContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * @author gene
 * ip工具
 */
@Slf4j
public class IPUtil {

    private static String ip;

    public static String getLocalIp() {
        if (StringUtils.isNotEmpty(ip)) {
            return ip;
        }

        try {
            ip = getLocalHostLANAddress().getHostAddress();
        } catch (UnknownHostException ue) {
            if (log.isErrorEnabled()) {
                log.error("can not get local Ip");
            }

            throw new RuntimeException("can not get local Ip");
        }

        return ip;
    }

    private static InetAddress getLocalHostLANAddress() throws UnknownHostException {
        try {
            InetAddress candidateAddress = null;
            // 遍历所有的网络接口
            for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) {
                NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
                // 在所有的接口下再遍历IP
                for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements(); ) {
                    InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                    // 排除loopback类型地址
                    if (!inetAddr.isLoopbackAddress()) {
                        if (inetAddr.isSiteLocalAddress()) {
                            // 如果是site-local地址，就是它了
                            return inetAddr;
                        } else if (candidateAddress == null) {
                            // site-local类型的地址未被发现，先记录候选地址
                            candidateAddress = inetAddr;
                        }
                    }
                }
            }
            if (candidateAddress != null) {
                return candidateAddress;
            }
            // 如果没有发现 non-loopback地址.只能用最次选的方案
            InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
            if (jdkSuppliedAddress == null) {
                throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
            }
            return jdkSuppliedAddress;
        } catch (Exception e) {
            UnknownHostException unknownHostException = new UnknownHostException(
                    "Failed to determine LAN address: " + e);
            unknownHostException.initCause(e);
            throw unknownHostException;
        }
    }

    /**
     * 是否本机ip
     *
     * @param ip
     * @return
     */
    public static boolean isLocalIp(String ip) {
        return getLocalIp().equals(ip);
    }

    /**
     * 是否ip和端口均为本地
     *
     * @param ip   ip
     * @param port port
     * @return boolean
     */
    public static boolean isLocalAddress(String ip, Integer port) {
        return isLocalIp(ip) && port.equals(LonpoStaticContext.getPort());
    }

}
